package com.example.shuqishixi;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
import org.json.JSONArray;
import org.json.JSONObject;

@WebServlet(name = "GetUserHistoryServlet", value = "/getUserHistoryServlet")
public class GetUserHistoryServlet extends HttpServlet {
    private static final String DB_URL = "jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true";
    private static final String DB_USER = "root";
    private static final String DB_PASSWORD = "123456";

    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("MySQL JDBC Driver not found", e);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();

        // 验证用户登录
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("username") == null) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            out.write("{\"error\":\"用户未登录\"}");
            return;
        }

        String currentUsername = (String) session.getAttribute("username");
        String currentRole = (String) session.getAttribute("user_role");
        String queryUsername = request.getParameter("username");

        // 权限验证：管理员可以查看所有用户历史，普通用户只能查看自己的
        // 权限验证：管理员可以查看所有用户历史，普通用户只能查看自己的
        if (queryUsername == null ||
                (!"admin".equals(currentRole) && !currentUsername.equals(queryUsername))) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            out.write("{\"error\":\"无权查看该用户历史记录\"}");
            return;
        }

        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD)) {
            String sql = "SELECT analysis_time, video_name, damaged_building, damaged_person, damaged_tree " +
                    "FROM video_analysis WHERE username = ? ORDER BY analysis_time DESC";

            try (PreparedStatement ps = conn.prepareStatement(sql)) {
                ps.setString(1, queryUsername);
                ResultSet rs = ps.executeQuery();

                JSONArray historyArray = new JSONArray();
                while (rs.next()) {
                    JSONObject record = new JSONObject();
                    record.put("analysis_time", rs.getTimestamp("analysis_time"));
                    record.put("video_name", rs.getString("video_name"));
                    record.put("damaged_building", rs.getInt("damaged_building"));
                    record.put("damaged_person", rs.getInt("damaged_person"));
                    record.put("damaged_tree", rs.getInt("damaged_tree"));
                    historyArray.put(record);
                }

                out.write(historyArray.toString());
            }
        } catch (SQLException e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            out.write("{\"error\":\"数据库查询失败\"}");
        }
    }
}